package server;

import java.io.*;

/**
 * @author yhy
 * @date 2021/3/16 15:57
 */
public class MyClassLoader extends ClassLoader {

    private String path;

    public MyClassLoader(String classPath) {
        path = classPath;
    }

    @Override
    public Class<?> findClass(String name) {
        Class classObject = null;
        String filePath = path + name.replaceAll("\\.", "/") + ".class";
        byte[] classData = getData(filePath);
        if (classData != null) {
            classObject = defineClass(name, classData, 0, classData.length);
        }
        return classObject;
    }

    private byte[] getData(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(file);
                out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return out.toByteArray();
        } else {
             return null;
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader("D:\\homework\\one_homework\\Minicat\\webapps\\demo-01\\");
        myClassLoader.findClass("servlet.DemoServlet");
    }
}
